<template>
  <div class="container">
    <base-title base-title="发布文章" />
    <mavon-editor v-model="mdContent" ref="mavonEditorRef" @imgAdd="imgAdd" @imgDel="imgDel" style="height: calc(80vh - 120px)" />
    <el-button type="primary" @click="articleSubmit" style="margin-top: 12px">提交</el-button>
    <ReleaseDialog ref="formInfo" :mdContent="mdContent" :types="types" :labels="labels" @uploadArticleSucceed="uploadArticleSucceed" />
  </div>
</template>

<script setup lang="ts" name="md">
  import { ref, reactive } from 'vue'
  import ReleaseDialog from './childComponents/ReleaseDialog.vue'
  import useArticleStore from '@/store/article'
  import notification from '@/utils/notification'
  import { SERVER_HOST, SERVER_PORT } from '@/constants/index'
  import { getAllTypesRequest } from '@/network/api/type-api'
  import { getAllLabelsRequest } from '@/network/api/label-api'
  import { uploadPicturesRequest, uploadArticleRequest } from '@/network/api/article-api'
  const mdContent = ref<string>('')
  const formInfo = ref(null)
  interface iPicture {
    [pos: number]: any
  }
  let img_file = reactive<iPicture>({})
  const articleStore = useArticleStore()
  const mavonEditorRef: any = ref(null)
  let labels = ref([])
  let types = ref([])
  // 上传文章配图到服务器
  const uploadImg = async (ref: any) => {
    const formdata = new FormData()
    for (const _img in img_file) {
      formdata.append('picture', img_file[_img])
    }
    const result = await uploadPicturesRequest(formdata)
    result.result.fileNames.forEach((item: string, index: number) => {
      const pictureUrl = `${SERVER_HOST}:${SERVER_PORT}/article/images/${item}`
      ref.$img2Url(index + 1, pictureUrl)
    })
    img_file = {}
  }
  // 缓存图片信息
  const imgAdd = (pos: number, file: any) => {
    img_file[pos] = file
  }
  // 删除某个图片缓存信息
  const imgDel = (pos: number) => {
    delete img_file[pos]
  }
  const articleSubmit = async () => {
    if (!mdContent.value.trim()) return notification.error('文章内容不能为空！')
    // 进行网络请求
    const labelsResult = await getAllLabelsRequest()
    labels.value = labelsResult.result
    const typesResult = await getAllTypesRequest()
    types.value = typesResult.result
    // 上传配图到服务器
    if (img_file) await uploadImg(mavonEditorRef.value)
    articleStore.articleVisibleController(true)
  }
  const uploadArticleSucceed = () => {
    mdContent.value = ''
  }
</script>

<style lang="less" scoped></style>
